use dto::address::AddressDTO;
use sea_orm::{ActiveModelBehavior, ActiveValue, DatabaseConnection};
use sky_pojo::{
    dto::{self, address::SearchDTO},
    entities::address_book::{self, ActiveModel, Model},
    vo::rows_warp,
};

use crate::mapper;

pub async fn list(db: &DatabaseConnection, dto: SearchDTO) -> Result<Vec<Model>, String> {
    mapper::address_book::list(db, dto)
        .await
        .map_err(|e| e.to_string())
}

//
pub async fn save(db: &DatabaseConnection, dto: AddressDTO, user_id: i64) -> Result<Model, String> {
    let mut model: address_book::ActiveModel = dto.into();
    model.user_id = ActiveValue::set(user_id);
    mapper::address_book::insert(db, model)
        .await
        .map_err(|e| e.to_string())
}

pub async fn get_by_id(db: &DatabaseConnection, id: i64) -> Result<Model, String> {
    mapper::address_book::get_by_id(db, id)
        .await
        .map_err(|e| e.to_string())
}

pub async fn update(
    db: &DatabaseConnection,
    dto: ActiveModel,
    user_id: i64,
) -> Result<Model, String> {
    let model = dto.into();
    mapper::address_book::update(db, model, user_id)
        .await
        .map_err(|e| e.to_string())
}

pub async fn set_default(db: &DatabaseConnection, id: i64, user_id: i64) -> Result<Model, String> {
    mapper::address_book::update_is_default_by_user_id(db, id, user_id)
        .await
        .map_err(|e| e.to_string())
}

pub async fn delete_by_id(db: &DatabaseConnection, id: i64, user_id: i64) -> Result<u64, String> {
    mapper::address_book::delete_by_id(db, id, user_id)
        .await
        .map(rows_warp)
        .map_err(|e| e.to_string())
}
